<?php
// ----------------------------------------------------------------------
// pn-commerce Shopping Cart Solution for PostNuke
// http://pncommerce.de
// http://www.sourceforge.net/projects/pn-commerce/
//
// It is based on PostKart 0.701QA from
//			Destin LeBlanc [ postkart@zenflesh.com ]
// ----------------------------------------------------------------------
// Source file:  $Source: /cvsroot/pn-commerce/pn-commerce/pnfmtaxapi.php,v $
//
// Last changes from:  $Author: landseer $
//
// Revision:           $Revision: 1.10 $
//
// Date of revision    $Date: 2004/07/28 15:07:09 $
//  
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------

/**
 * getConfig
 *@param  none
 *@return array of config values
 */
function pncommerce_fmtaxapi_getConfig()
{
    $data = pnModGetVar ( 'pncommerce', 'fmtaxData' );
    if( isset( $data ) )
    {
        return unserialize( $data );
    }
    return false;
}

/**
 * setConfig
 *@param  $args array of config values
 *@return none
 */
function pncommerce_fmtaxapi_setConfig( $args )
{
    pnModSetVar ( 'pncommerce', 'fmtaxData', serialize( $args ) );
    unset($args);
}

/**
 * configuration
 *
 */
function pncommerce_fmtaxapi_configuration()
{
    if( !pnModAPILoad( 'pncommerce', 'admin' ) )
    {
        return false;
    }
    if( !pnModAPILoad( 'pncommerce', 'user' ) )
    {
        return false;
    }
    
    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN))
    {
        return pnModAPIFunc( 'pncommerce', 'admin','GetErrorPage',array('Title'=>_PNC_NOAUTH));
    }

    $config = pncommerce_fmtaxapi_getConfig();

    for($x=0;$x<count($config['Taxes']);$x++)
    {
        if( $config['Taxes'][$x]['TaxSH'] == 'on' )
        {
            $config['Taxes'][$x]['TaxSHHTML'] = 'checked';
        }
        if( $config['Taxes'][$x]['Condition'] == 'city' )
        {
            $config['Taxes'][$x]['Condition1HTML'] = 'checked';
            $config['Taxes'][$x]['Condition2HTML'] = '';
            $config['Taxes'][$x]['Value1'] = $config['Taxes'][$x]['Value'];
            $config['Taxes'][$x]['Value2'] = '';
        }
        elseif( $config['Taxes'][$x]['Condition'] == 'state' )
        {
            $config['Taxes'][$x]['Condition1HTML'] = '';
            $config['Taxes'][$x]['Condition2HTML'] = 'checked';
            $config['Taxes'][$x]['Value1'] = '';
            $config['Taxes'][$x]['Value2'] = $config['Taxes'][$x]['Value'];
        }
    }

    list( $submit, $submit2 ) = pnVarCleanFromInput( 'submit', 'submit2' );
    
    if( (!$submit) && (!$submit2) )
    {
        $smarty =& new pnRender('pncommerce');
        $smarty->caching = false;
        $UseCountry[$config['UseCountry']] = 'selected';
        $smarty->assign( 'UseCountryHTML', $UseCountry );
        $smarty->assign( 'FederalStateList', pnModAPIFunc( 'pncommerce', 'user', 'getFederalStateListForSelect', 
                          array( 'Country' => $config['UseCountry'],
                                 'Format'  => 'short' ) ) );
        $smarty->assign( 'TaxCount', count( $config['Taxes'] ) );
        $smarty->assign( 'TaxConfig', $config );
        $smarty->assign( 'USA', _PNC_USA );
        $smarty->assign( 'Canada', _PNC_CANADA );
        return $smarty->fetch( "pncommerce_fmtax_configuration.html" );
    }
    else   // one of the submits is set
    {
        $storage = array();
        if( $submit )
        {
            $taxarray = array();
            // cycle through the old taxarray
            for($x=0;$x<count($config['Taxes']);$x++)
            {
                $oldtaxname = $config['Taxes'][$x]['Name'];
                $remove = pnVarCleanFromInput( 'remove_'.$oldtaxname );
                if( $remove <> 'on' )
                {
                    // do not ignore this
                    list( $name, $percentage, $condition,
                          $value1, $value2, $taxsh ) =
                          pnVarCleanFromInput ( 'name_'.$oldtaxname, 'percentage_'.$oldtaxname,
                                                'condition_'.$oldtaxname, 'value1_'.$oldtaxname,
                                                'value2_'.$oldtaxname, 'taxsh_'.$oldtaxname );
                    $tax = array( 'Name'         => $name,
                                  'Percentage'   => $percentage,
                                  'TaxSH'        => $taxsh,
                                  'Condition'    => $condition );
                    if( $condition == 'city' )
                    {
                        $tax['Value'] = $value1;
                    }
                    elseif( $condition == 'state' )
                    {
                        $tax['Value'] = $value2;
                    }
                    array_push( $taxarray, $tax );
                }
            }
            
            // now read the _new tax that may ave been added
            list( $new_name, $new_percentage, $new_condition,
                  $new_value1, $new_value2, $new_taxsh ) =
                  pnVarCleanFromInput ( 'name_new', 'percentage_new', 'condition_new',
                                        'value1_new', 'value2_new', 'taxsh_new' );
            if( $new_name <> "" )
            {
                $newtax = array( 'Name'         => $new_name,
                                 'Percentage'   => $new_percentage,
                                 'TaxSH'        => $new_taxsh,
                                 'Condition'    => $new_condition );
                if( $new_condition == 'city' )
                {
                    $newtax['Value'] = $new_value1;
                }
                elseif( $new_condition == 'state' )
                {
                    $newtax['Value'] = $new_value2;
                }
                array_push( $taxarray, $newtax );
            }
            $storage['Taxes'] = $taxarray;
            $storage['UseCountry'] = $config['UseCountry'];

    	    pncommerce_fmtaxapi_setConfig( $storage );
    	    unset( $storage );
    	    unset( $config );
    	    pnRedirect( pnModAPIFunc( 'pncommerce','user','pncModURL',
	    							  array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'ModificationConfig')));
	        return true;
        }
        elseif( $submit2 )
        {
            $storage = $config;
            $storage['UseCountry'] = pnVarCleanFromInput( 'usecountry' );
	        pncommerce_fmtaxapi_setConfig( $storage );
    	    unset( $storage );
    	    unset( $config );
    	    pnRedirect( pnModAPIFunc( 'pncommerce','user','pncModURL',
	    							  array('Module'=>'pncommerce', 'Section'=> 'fmtaxapi', 'Function'=>'configuration')));
	        return true;
        }
    }

}

/**
 * checkout
 *@param $args['CartItems'] array complete array with cart data
 *@param $args['WeightTotal'] complete weight of all items
 *@param $args['ItemsTotal'] number of items
 *@param $args['SubTotal'] total value of items (no additional costs included
 *@param $args['ShippingTotal'] shipping costs
 *@param $args['PaymethodTotal'] paymethod costs
 *@param $args['OrderModifiers'] array of previously used ordermodifiers, e.g. handling before tax.
 *@return amount
 */
function pncommerce_fmtaxapi_checkout($args)
{
    extract( $args );
    $config = pncommerce_fmtaxapi_getConfig();

    foreach( $CartItems as $item )
    {
        if( $item['TaxExempt'] <> 'on' )
        {
            $TaxSum += $item['ItemCostTotal'];
        }
    }
    // $TaxSum now contains the total of all items that the customer has to pay taxes for
    $userdata = unserialize( pnSessionGetVar( 'PNCUserData' ) );
    if( $userdata['Business'] == 1 )
    {
        return 0;
    }  
    // now for the tax and shipping and handling
    $taxamount = 0;
    foreach( $config['Taxes'] as $Tax )
    {
        if( $Tax['TaxSH'] == 'on' )
        {
            // add the shipping costs
            $TaxSum2 = $TaxSum + $ShippingTotal;
            foreach( $OrderModifiers as $modifier )
            {
                if( $modifier['Name'] == 'fmhandling' )
                {
                    // add the handling costs
                    $TaxSum2 = $TaxSum2 + $modifier['Amount'];
                }
            }
        }
        else
        {
            $TaxSum2 = $TaxSum;
        }
        
        switch( $Tax['Condition'] )
        {
            case 'city':
                    if( strtoupper( $userdata['City'] ) == strtoupper( $Tax['Value'] ) )
                    {
                        $taxamount += ( $TaxSum2 / 100 ) * $Tax['Percentage'];
                    }
                    break;
            case 'state':
                    if( $userdata['State'] == $Tax['Value'] )
                    {
                        $taxamount += ( $TaxSum2 / 100 ) * $Tax['Percentage'];
                    }
                    break;
            default:
                    // we should not get here, but we need a default
                    return 0;
        }
    }
    return $taxamount;
}


/**
 * info
 *
 */
function pncommerce_fmtaxapi_info()
{
    return (_PNC_TAX);
}

/**
 * type
 *
 */
function pncommerce_fmtaxapi_type()
{
    return ( _PNC_MODIFIERPERORDER );
}

/**
 * FooterMsg
 *
 */
function pncommerce_fmtaxapi_FooterMsg()
{
    return false;
}

/**
 * installation
 *
 *@param $args['Mode'] string  install, remove activate or deactivate
 *
 */
function pncommerce_fmtaxapi_installation($args)
{
    extract( $args );
    $Mode = pnVarCleanFromInput( 'Mode' );
    if( !pnModAPILoad( 'pncommerce', 'user' ) )
    {
        return false;
    }

    if (!pnSecAuthAction(0, 'pncommerce::', '::', ACCESS_ADMIN))
    {
        return pnModAPIFunc( 'pncommerce', 'user', 'GetErrorPage',array('Title'=>_PNC_NOAUTH));
    }

    switch( $Mode )
    {
        case 'install':
                    pnModSetVar( 'pncommerce', 'fmtax', 'on' );
                    pnModSetVar( 'pncommerce', 'fmtaxData', serialize ( array ( 'UseCountry' => "usa" ) ) );
                    pnModAPIFunc( 'pncommerce', 'admin', 'addtoModifierSequence',
                                  array( 'Modifier' => 'fmtax',
                                         'type'     => 'order' ) );
                    break;
        case 'remove':
                    pnModDelVar( 'pncommerce', 'fmtax' );
                    pnModDelVar( 'pncommerce', 'fmtaxData' );
                    pnModAPIFunc( 'pncommerce', 'admin', 'removefromModifierSequence',
                                  array( 'Modifier' => 'fmtax',
                                         'type'     => 'order' ) );
                    break;
        case 'activate':
                    pnmodSetVar( 'pncommerce', 'fmtax', 'on' );
                    break;
        case 'deactivate':
                    pnModSetVar( 'pncommerce', 'fmtax', 'off' );
                    break;
        default:
                    return false;
    }
    pnRedirect( pnModAPIFunc( 'pncommerce','user','pncModURL',
                              array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'ModificationConfig')));
    return true; 
}               


?>
